package server

import (
	"github.com/akirakazu/go-simplejson"
)

// Find a conn by target id
// excluding self id
func (s *Server) findConn(targetId, selfId *json.Json) (string, bool) {
	for k, v := range s.conns {
		if PatternMatch(targetId, v.identity) {
			if !PatternMatch(v.identity, selfId) {
				return k, true
			}
		}
	}
	return "", false
}

// Find a conn by target id
func (s *Server) findConnWithoutSelfId(targetId *json.Json) (string, bool) {
	for k, v := range s.conns {
		if PatternMatch(targetId, v.identity) {
			return k, true
		}
	}
	return "", false
}

// Find conns by target id
func (s *Server) findConns(target, origin *json.Json) []string {
	arr := []string{}
	for k, v := range s.conns {
		if PatternMatch(target, v.identity) {
			if !PatternMatch(v.identity, origin) {
				arr = append(arr, k)
			}
		}
	}
	return arr
}

func (s *Server) allProxies(vias []string) []string {
	arr := []string{}
	for k, _ := range s.conns {
		if s.isProxyConn(k) {
			arr = append(arr, k)
		}
	}
	return arr
}

func (s *Server) findProxy(excludes []string, vias []string, ccuId string) string {
	if s.proxy != nil && s.proxy.ready && !s.itemExists(s.proxy.id, excludes) && !s.itemExists(s.proxy.id, vias) {
		return PROXY_ID
	}

	if ccuId != "" {
		for k, v := range s.conns {
			sessionId, err := v.identity.GetString("session_id")
			if err != nil {
				continue
			}
			if s.isProxyConn(k) && !s.itemExists(sessionId, excludes) && !s.itemExists(sessionId, vias) && ccuId == sessionId {
				return k
			}
		}
	}

	for k, v := range s.conns {
		sessionId, err := v.identity.GetString("session_id")
		if err != nil {
			continue
		}
		if s.isProxyConn(k) && !s.itemExists(sessionId, excludes) && !s.itemExists(sessionId, vias) {
			return k
		}
	}
	return ""
}

func (s *Server) itemPos(item string, arr []string) int {
	for i, v := range arr {
		if v == item {
			return i
		}
	}
	return -1
}

func (s *Server) itemExists(item string, arr []string) bool {
	if s.itemPos(item, arr) == -1 {
		return false
	} else {
		return true
	}
}
